import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘国水
 * Date: 2025-05-18
 * Time: 22:25
 */
public class test {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void init(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void createHeap() {
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, usedSize);
        }
    }

    private void siftDown(int parent, int usedSize) {
        //计入左孩子下标
        int child = 2 * parent+1;

        while (child < usedSize) {
            //左右孩子进行比较 计入child的最大值
            if(child+1 < usedSize && elem[child] < elem[child+1]) {
                child++;
            }
            //左右孩子的最大值和根节点进行比较 然后交换
            if(elem[child] > elem[parent]) {
                swap(elem,child,parent);
                parent = child;
                child = 2 * parent+1;
            } else {
                break;
            }
        }
        //左右孩子进行比较 计入child的最大值

        //左右孩子的最大值和根节点进行比较 然后交换
//        int child = 2 * parent+1;
//
//        while (child < usedSize) {
//
//            if(child+1 < usedSize && elem[child] < elem[child+1]) {
//                child++;
//            }
//            if(elem[child] > elem[parent]) {
//                swap(elem,child,parent);
//                parent = child;
//                child = 2 * parent+1;
//            } else  {
//                break;
//            }
//        }
    }

    private void swap(int[] elem, int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = val;
        usedSize++;
        //调整
        siftUp(usedSize-1);

    }

    private void siftUp(int child) {
        int parent = (child-1)/2;
        while (child > 0) {

            if(elem[child] > elem[parent]) {
                swap(elem,child,parent);
                child = parent;
                parent = (child-1)/2;
            } else  {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    public int poll() {
        if(isEmpty()) {
            return -1;
        }
        int ret = elem[0];
        swap(elem,0,usedSize-1);
        usedSize--;
        siftDown(0,usedSize);
        return ret;
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    public int peek() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }

}
